package main

import (
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"syscall"

	"gitee.com/kitfast/appml"
	"gopkg.in/yaml.v3"
)

func exitIfErr(err error) {
	if err == nil {
		return
	}
	buf := make([]byte, 1024*1024)
	log.Printf("Error: %v\nStack: \n%s", err, string(buf[:runtime.Stack(buf, true)]))
}

func loadConfig(fn string) *appml.Config {
	cf, err := os.Open(fn)
	if err != nil {
		exitIfErr(err)
	}
	defer cf.Close()
	cnf := &appml.Config{}
	if err := yaml.NewDecoder(cf).Decode(cnf); err != nil {
		exitIfErr(err)
	}
	return cnf
}

func main() {
	exe, _ := os.Executable()
	cnf := loadConfig(filepath.Join(filepath.Dir(exe), "config.yml"))
	mgr, err := appml.NewAppManager(cnf)
	if err != nil {
		exitIfErr(err)
	}
	if mgr != nil {
		defer mgr.Close()
	}

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	<-signals
}
